package com.adb.receivecontent.utility;

import java.io.File;
import java.util.ArrayList;

import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

import android.content.Context;

import com.adb.receivecontent.bean.LinkMagnetBean;
import com.adb.receivecontent.bean.LinkParam;
import com.adb.receivecontent.uc.IPubliceProgress;
import com.adb.receivecontent.utility.CustomMultiPartEntity.ProgressListener;

public class HttpMultiPartEntitiy {
	
	long totalSize;
	IPubliceProgress mProgressCallBack;
	public HttpMultiPartEntitiy() {
	}
	
	public String postImageIMEI(Context mContext, String vLocalPath,
			LinkMagnetBean vBeanApdater) {
		
		mProgressCallBack = (IPubliceProgress)mContext;
		ArrayList<LinkParam> mParamArrayList;
		String responseMessage = null;
		
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost(vBeanApdater.getStrlinkurl());
				
		try {
			
			CustomMultiPartEntity multipartContent = new CustomMultiPartEntity(new ProgressListener() {
				
				@Override
				public void transferred(long num) {
					mProgressCallBack.setPubliseProgress(((int) ((num / (float) totalSize) * 100)));
				}
			});
	        
			mParamArrayList = vBeanApdater.getmArrayListParams();
	        if(mParamArrayList != null){
	        
	        	for(int i =0;i<mParamArrayList.size();i++){
	        		
	        		LinkParam mTempParams = mParamArrayList.get(i);
	        		multipartContent.addPart(mTempParams.getStrKey(),new StringBody(mTempParams.getStrValue()));	
		        }
	        }
	        
			
	        FileBody bin = new FileBody(new File(vLocalPath));
	        multipartContent.addPart(vBeanApdater.getStrFileName(), bin); //thefile
			totalSize = multipartContent.getContentLength();
			
			httppost.setEntity(multipartContent);

			System.out.println("Requesting : " + httppost.getRequestLine());
			ResponseHandler<String> responseHandler = new BasicResponseHandler();
			String responseBody = httpclient.execute(httppost, responseHandler);

			responseMessage = responseBody;
			System.out.println("responseBody : " + responseBody);
			
		} catch (Exception e) {
			return e.getMessage();
		} finally {
			
			httpclient.getConnectionManager().shutdown();
		
		}
		return responseMessage;
	}

}
